'''
Created on 20 juil. 2011

@author: nathanael
'''

from enthought.traits.api \
    import HasTraits, Unicode, Instance, HTML, Property, Button, Int, Unicode, \
           Any, List, Interface, implements, cached_property

from enthought.traits.ui.api \
    import TreeEditor, TreeNode, View, Item, \
           VGroup, HGroup, Handler, Group, HSplit, VSplit, ListEditor
    

from pybible.core.html.viewer import Viewer
from pybible.core.result import XResult, Results

from lxml import etree
    
class UIResultI(Interface):
    "Interface for a result"
    
class UIResultsI(Interface):
    "Interface for a results container"
    
    def __iter__(self):
        ""
    
    def append(self, r):
        ""
        
    def extend(self, results):
        ""
        
    def clear(self):
        ""
    
    
class _TXT_UIResult(HasTraits):#, Viewer):
    implements(UIResultI)
    
    txt = Property(trait=Unicode)
    result = Any
    booksname = Any
    data = Any
    view = View(
             Group(
               Item('txt',
                    show_label=False,
                    resizable=True,
                    style="readonly"),
               ),
             resizable=True,
             )
    def _get_txt(self):
        verse = self.data.eval_xpath(self.result.get_xpath())[0]
        chapter = verse.get_parent()
        book = chapter.get_parent()
    
        return u"%s %d.%d: %s" % (self.booksname[book.get_id()],
                                  chapter.get_id(),
                                  verse.get_id(),
                                  verse.text) 


class _UIResult_HTML(HasTraits):#, Viewer):
    "To show a result into HTML view."
    implements(UIResultI)
    
    html = Property(trait=HTML)
    result = Any
    booksname = Any
    data = Any
    view = View(
             Group(
               Item('html',
                    show_label=False,
                    resizable=True,
                    style="readonly"),
               ),
             resizable=True,
             )
    
    def get_html_ampty(self):
        "Return html roor and body node."
        html = etree.Element('html')
        head = etree.Element('head')
        html.append(head)
        body = etree.Element('body')
        html.append(body)
        return html, head, body

    @cached_property
    def _get_html(self):
        verse = self.result.element
        chapter = verse.get_parent()
        book = chapter.get_parent()
    
        # build a page
        html, header, body = self.get_html_ampty()

        # define my stype
        stype = etree.Element('style', {'type':'text/css'})
        stype.text = ".vers_id {font-weight:bold; color:blue;}"
        header.append(stype) 

        
        # write verse
        vers_header = etree.Element('div')
        body.append(vers_header)
        vers_num = etree.Element('span', {'class':'vers_id'})
        vers_header.append(vers_num)
        vers_num.text = u"%s %d.%d:" % (self.booksname[book.get_id()],
                                          chapter.get_id(),
                                          verse.get_id())
        vers = etree.Element('span', {'class':'vers_text'})
        vers_header.append(vers)
        vers.text = verse.text 
        
        return etree.tounicode(html)
      
        
def UIResult_HTML(data, booksname, element, xpath, regex, ref=None):
    "Default factory to build HTML view of a result."
    return _UIResult_HTML(data=data,
                          booksname=booksname,
                          result=(XResult(element, xpath, regex, ref)))
    

def UIResults_HTML(results=[]):
    "Build a new UI view for results list or Results instance."
    if isinstance(results, _UIResults_HTML):
        return  _UIResults_HTML(values=results.values)
    elif isinstance(results, _UIResults_HTML):
        return results
    return  _UIResults_HTML(values=results)


class _UIResults_HTML(HasTraits):
    "Object store all results"
    implements(UIResultsI)
    
    values = List(Instance(UIResultI))#, depend_on=('append',))
    
    view = View(
             Group(
                Item('values',
                    show_label=False,
                    resizable=True,
                    style="readonly",
                    editor=ListEditor(style='custom')
                    )
               ),
             resizable=True,
             )
    
    def __iter__(self):
        return iter(self.values)
    
    def append(self, r):
        self.values.append(r)
        
    def extend(self, results):
        self.values.extend(results)
        
    def clear(self):
        self.values = []
        return self


class UIResults_HTML_factory(object):
    def __init__(self, bookname=None, data=None):
        self.reinit(bookname, data)
        
    def reinit(self, booksname=None, data=None):
        self.data = data
        self.booksname = booksname
        
    def new_result(self, element, xpath, regex, ref):
        "Method to build valid result."
        return UIResult_HTML(self.data, self.booksname,
                             element, xpath, regex, ref)
    
    def new_results(self, *argv, **kw):
        "build a new results container."
        return UIResults_HTML(*argv, **kw)
    
































class _UIResults_text(HasTraits):
    "Object store all results"
    implements(UIResultsI)
    
    values = List(Unicode, depend_on=('extend'))
    
    view = View(
             Group(
                Item('values',
                    show_label=False,
                    resizable=True,
                    #style="readonly",
                    editor=ListEditor(style='custom')
                    )
               ),
             resizable=True,
             )
    
    def __iter__(self):
        return iter(self.values)
    
    def append(self, r):
        self.values.append(r)
        
    def extend(self, results):
        self.values.extend(results)
        
    def clear(self):
        self.values = []
        return self




class UIResults_text_factory(object):
    def __init__(self, bookname=None, data=None):
        self.reinit(bookname, data)
        
    def reinit(self, booksname=None, data=None):
        self.data = data
        self.booksname = booksname
        
    def new_result(self, element, xpath, regex, ref):
        "Method to build valid result."
        verse = element
        chapter = verse.get_parent()
        book = chapter.get_parent()
    
        return u"%s %d.%d: %s" % (self.booksname[book.get_id()],
                                  chapter.get_id(),
                                  verse.get_id(),
                                  verse.text)
        
    def new_results(self, *argv, **kw):
        "build a new results container."
        return UIResults_HTML(*argv, **kw)




class _UIResult_text2(HasTraits):#, Viewer):
    "To show a result into HTML view."
    implements(UIResultI)
    
    text = Unicode
    
    view = View(
             Group(
               Item('text',
                    show_label=False,
                    resizable=True,
                    style="readonly"),
               ),
             resizable=True,
             )


class UIResults_text_factory2(UIResults_text_factory):
    def __init__(self, bookname=None, data=None):
        self.reinit(bookname, data)
        
    def reinit(self, booksname=None, data=None):
        self.data = data
        self.booksname = booksname
        
    def new_result(self, element, xpath, regex, ref):
        "Method to build valid result."
        verse = element
        chapter = verse.get_parent()
        book = chapter.get_parent()
    
        return _UIResult_text2\
            (text=u"%s %d.%d: %s" % (self.booksname[book.get_id()],
                                     chapter.get_id(),
                                     verse.get_id(),
                                     verse.text))
        
    def new_results(self, *argv, **kw):
        "build a new results container."
        return UIResults_HTML(*argv, **kw)

